<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Upload_private extends wsFrontend
{

    public function __construct()
    {
        parent::__construct();
        if (strpos(strtolower($this->uri->uri_string()), 'upload_private') !== false) {
            redirect();
        }
        if (!$this->user->is_loggedIn()) {
            $this->session->set_flashdata('MESSAGE', '您需要登陆才可以上传壁纸');
            redirect($this->route_links->get('account_login'));
        }
    }

    public function index()
    {
        $data = array();
        $this->tpl->meta ['title'] = $this->metadata->get_metadata('_upload_page_title', 'upload_page');
        $this->tpl->meta ['description'] = $this->metadata->get_metadata('_upload_page_description', 'upload_page');
        $this->tpl->meta ['keywords'] = $this->metadata->get_metadata('_upload_page_keyword', 'upload_page');

        $this->load->model(array('category_model', 'wallpaper_model'));

        $this->db->custom_seqgment('search', 'index');
        $data['categories'] = $this->category_model->get_categoryDropDownTree();
        $this->db->reset_custom_seqgment();


        $this->load->library('form_validation');
        $this->form_validation->set_rules('image_name', $this->language->get_text('image-name','upload'), 'trim');
        $this->form_validation->set_rules('publish', $this->language->get_text('image-status','upload'), 'required');
        $this->form_validation->set_rules('category', $this->language->get_text('category','global'), 'required');
        if ($this->input->post('author_url'))
            $this->form_validation->set_rules('author_url', $this->language->get_text('author-url','account'), 'required');

        $data['image'] = false;
        $temp_image = $this->input->post('temp_image_path');
        if ($temp_image && file_exists(FCPATH . $temp_image))
            $data['image'] = $temp_image;


        if (!empty($_POST)) {
            if (!$data['image']) {
                if ($this->input->post('upload_by') == 'file' && (isset($_FILES['file']['error']) && $_FILES['file']['error'] == UPLOAD_ERR_OK)) {
                    $config['upload_path'] = FULL_TEMP . DS . $this->user->get_id();
                    if (!is_dir($config['upload_path']))
                        mkdir($config['upload_path'], 0777, true);
                    $config['allowed_types'] = 'gif|jpg|png';
                    $config['max_size'] = MAX_SIZE;
                    $config['overwrite'] = TRUE;
                    if ($this->config->item('minimum_width'))
                        $config['min_width'] = $this->config->item('minimum_width');
                    if ($this->config->item('minimum_height'))
                        $config['min_height'] = $this->config->item('minimum_height');
                    $this->load->library('upload', $config);
                    if (!$this->upload->do_upload('file')) {
                        $data['error'][] = $this->upload->display_errors();
                    } else {
                        $upload_data = $this->upload->data();
                        $data['image'] = FULL_TEMP_RAW . DS . $this->user->get_id() . DS . $upload_data['file_name'];
                    }
                } elseif ($this->input->post('upload_by') == 'url') {
                    $headers = @get_headers($this->input->post('file_url'), TRUE);
                    if (!$headers) {
                        $data['error'][] = $this->language->get_text('unable-to-connect-server','upload');
                    } else {
                        if (!isset($headers['Content-Type']) || (isset($headers['Content-Type']) && !in_array(strtolower($headers['Content-Type']), array('image/jpeg', 'image/png')))) {
                            $data['error'][] = $this->language->get_text('IFFAOJOP','upload');
                        } else {
                            $image_info = GetImageInfo_($this->input->post('file_url'), 'http_Curl');
                            if ($image_info['width'] < $this->config->item('minimum_width') || $image_info['height'] < $this->config->item('minimum_height')) {
                                $data['error'][] = $this->language->get_text('minimum-image-size-required','upload') . $this->config->item('minimum_width') . 'x' . $this->config->item('minimum_height');
                            } else {
                                if (!is_dir(FULL_TEMP . DS . $this->user->get_id()))
                                    mkdir(FULL_TEMP . DS . $this->user->get_id(), 0777, true);
                                $save_path = DS . $this->user->get_id() . '/' . $image_info['pathInfo']['basename'];
                                download_file($this->input->post('file_url'), FULL_TEMP . $save_path);
                                $data['image'] = FULL_TEMP_RAW . $save_path;
                            }
                        }
                    }
                }
            }


            $image_name = $this->input->post('image_name');
            if (!$image_name)
                $image_name = pathinfo($data['image'], PATHINFO_FILENAME);
            $clean_name = str_replace(array('_', '-'), ' ', $image_name);
            $clean_name = cleanImageName(preg_replace('/\s+/im', ' ', $clean_name));
            $_POST['image_name'] = $clean_name;

            $tags = $this->input->post('tags');
            if (!$tags)
                $_POST['tags'] = join(',', explode(' ', $clean_name));
        }


        if ($this->form_validation->run() && empty($data['error']) && $data['image']) {

            if (!array_key_exists($this->input->post('category'), $data['categories'])) {
                $data['error'][] = $this->language->get_text('ICISCIINE','upload');
            }

            if (empty($data['error'])) {
                //Move File
                $dateFolder = date('Y/m/d/');
                $new_path = ORIGINALS_FOLDER_WF . DS . $dateFolder;
                if (!is_dir($new_path))
                    mkdir($new_path, 0777, true);
                $new_path .= basename($data['image']);
                $imageInfo = GetImageInfo_($data['image'], 'default');
                $move_file_name = $this->image_workshop->move_file(FCPATH . $data['image'], FCPATH . $new_path);
				$slug = "abc";
                $insert_data = array(
                    'wallpaper_name' => $clean_name,
                    'wallpaper_slug' => $slug,
                    'user_seq_id' => $this->user->get_id(),
                    'category_seq_id' => $this->input->post('category'),
                    'wallpaper_image_path' => $dateFolder . $move_file_name,
                    'wallpaper_width' => $imageInfo['width'],
                    'wallpaper_height' => $imageInfo['height'],
                    'wallpaper_status' => ($this->input->post('publish') ? 1 : 0),
                    'wallpaper_featured' => 0,
                    'wallpaper_approved' => ($this->user->is_admin() ? 1 : ($this->config->item('auto_approve_users_updated_wallpapers'))),
                    'wallpaper_description' => (strip_tags($this->input->post('description')) != '' ? $this->input->post('description') : NULL),
                    'wallpaper_date_created' => date('Y:m:d H:i:s'),
                    'wallpaper_metatitle' => $this->input->post('metaTitle'),
                    'wallpaper_metadescription' => $this->input->post('metaDescription'),
                    'wallpaper_metakeywords' => $this->input->post('metaKeywords'),
                    'wallpaper_author' => $this->input->post('author'),
                    'wallpaper_author_site' => $this->input->post('author_url'),
                    'wallpaper_crop_position' => in_array($this->input->post('image_position'), $this->image_workshop->positions) ? $this->input->post('image_position') : 'MM',
                );

                $insert_id = $this->wallpaper_model->insert($insert_data);
                $hash = $this->hashids->encrypt($insert_id);
                $update = array(
                    'wallpaper_hash' => $hash,
                );
                $this->wallpaper_model->update($update, array('wallpaper_seq_id' => $insert_id));

                $this->load->library(array('colors_extract', 'colors_tool'));
                $colors = $this->colors_extract->get_Color(ORIGINALS_FOLDER . DS . $insert_data['wallpaper_image_path']);
                if ($colors) {
                    $bulk_colors = array();
                    foreach ($colors as $color => $count_percentage) {
                        $hsl = colors_tool::hexToHsl($color);
                        $bulk_colors[] = array(
                            'wallpaper_seq_id' => $insert_id,
                            'count' => $count_percentage,
                            'hex_code' => $color,
                            'hue' => $hsl['H'],
                            'saturation' => $hsl['S'],
                            'lightness' => $hsl['L'],
                        );
                    }
                    if (!empty($bulk_colors))
                        $this->wallpaper_model->insert_colors($bulk_colors, true);
                }


                $tags = explode(',', $this->input->post('tags'));
                $tags = array_filter($tags);
                if (!empty($tags)) {
                    $insert_tags = array();
                    foreach ($tags as $t) {
                        $t = trim($t);
                        $insert_tags[] = array(
                            'wallpaper_seq_id' => $insert_id,
                            'tag_name' => url_title_no_space($t, '-', true),
                        );
                    }
                    if (!empty($insert_tags))
                        $this->wallpaper_model->insertTags($insert_tags, true);
                }
                $this->session->set_flashdata('SUCCESS', $this->language->get_text('wallpaper-uploaded-successfully','upload'));
                if (isset($_POST['upload_image_edit'])) {
                    redirect($this->route_links->get('upload_wallpaper_edit', array('{hash}' => $hash)));
                } else {
                    redirect($this->route_links->get('upload_wallpaper'));
                }
            }
        }

        $data['wallpaper'] = false;

        $this->tpl->breadcrumbs['上传壁纸'] = 'active';

        $this->tpl->contents [] = $this->tpl->fetch('contents/upload_page', $data);
        $this->tpl->render('layouts/home');
    }


    public function edit($hash = false)
    {
        if (!$hash)
            redirect($this->route_links->get('upload_wallpaper'));

        $data = array();
        $this->tpl->meta ['title'] = $this->metadata->get_metadata('_upload_page_title', 'upload_page');
        $this->tpl->meta ['description'] = $this->metadata->get_metadata('_upload_page_description', 'upload_page');
        $this->tpl->meta ['keywords'] = $this->metadata->get_metadata('_upload_page_keyword', 'upload_page');

        $this->load->model(array('category_model', 'wallpaper_model'));
        $this->db->custom_seqgment('search', 'index');
        $data['categories'] = $this->category_model->get_categoryDropDownTree();
        $this->db->reset_custom_seqgment();

        $data['wallpaper'] = $this->wallpaper_model->get_wallpaper(array(
            'user_seq_id' => $this->user->get_id(),
            'wallpaper_hash' => $hash,
            'cache_off' => true
        ));

        if (!$data['wallpaper']) {
            $this->session->set_flashdata('ERROR', '壁纸ID有误');
            redirect($this->route_links->get('upload_wallpaper'));
        }
        $data['search_replace'] = array(
            '{C_SLUG_FULL}' => $data['wallpaper']->cFullSlug,
            '{C_SLUG}' => $data['wallpaper']->category_slug,
            '{W_SLUG}' => $data['wallpaper']->wallpaper_slug,
            '{W_HASH}' => $data['wallpaper']->wallpaper_hash,
        );

        $data['url'] = $this->route_links->build_link('wallpaper_page', $data['search_replace']);

        $data['image'] = ORIGINALS_FOLDER_WF . '/' . $data['wallpaper']->wallpaper_image_path;

        $this->load->library('form_validation');
        $this->form_validation->set_rules('image_name', $this->language->get_text('image-name','upload'), 'trim');
        $this->form_validation->set_rules('publish', $this->language->get_text('image-status','upload'), 'required');
        $this->form_validation->set_rules('category', $this->language->get_text('category','global'), 'required');
        if ($this->input->post('author_url'))
            $this->form_validation->set_rules('author_url', $this->language->get_text('author-url','account'), 'required');

        if (!empty($_POST)) {
            $tags = $this->input->post('tags');
            if (!$tags)
                $_POST['tags'] = join(',', explode(' ', $this->input->post('image_name')));
        }


        if ($this->form_validation->run() && empty($data['error']) && $data['image']) {

            if (!array_key_exists($this->input->post('category'), $data['categories'])) {
                $data['error'][] = $this->language->get_text('ICISCIINE','upload');
            }

            if (empty($data['error'])) {
                $update_data = array(
                    'wallpaper_name' => $this->input->post('image_name'),
                    'wallpaper_slug' => build_slug($this->input->post('image_name')),
                    'category_seq_id' => $this->input->post('category'),
                    'wallpaper_status' => ($this->input->post('publish') ? 1 : 0),
                    'wallpaper_description' => (strip_tags($this->input->post('description')) != '' ? $this->input->post('description') : NULL),
                    'wallpaper_date_modified' => date('Y:m:d H:i:s'),
                    'wallpaper_metatitle' => $this->input->post('metaTitle'),
                    'wallpaper_metadescription' => $this->input->post('metaDescription'),
                    'wallpaper_metakeywords' => $this->input->post('metaKeywords'),
                    'wallpaper_author' => $this->input->post('author'),
                    'wallpaper_author_site' => $this->input->post('author_url'),
                    'wallpaper_crop_position' => in_array($this->input->post('image_position'), $this->image_workshop->positions) ? $this->input->post('image_position') : 'MM',
                );

                $this->wallpaper_model->update($update_data, array('wallpaper_seq_id' => $data['wallpaper']->wallpaper_seq_id));
                $tags = explode(',', $this->input->post('tags'));
                $tags = array_filter($tags);
                if (!empty($tags)) {
                    $insert_tags = array();
                    foreach ($tags as $t) {
                        $t = trim($t);
                        $insert_tags[] = array(
                            'wallpaper_seq_id' => $data['wallpaper']->wallpaper_seq_id,
                            'tag_name' => url_title($t, true, '-'),
                        );
                    }
                    $this->wallpaper_model->deleteWallTags(array($data['wallpaper']->wallpaper_seq_id));
                    if (!empty($insert_tags))
                        $this->wallpaper_model->insertTags($insert_tags, true);
                }

                $this->session->set_flashdata('SUCCESS', '壁纸上传成功');
                if (isset($_POST['upload_image_edit'])) {
                    redirect($this->route_links->get('upload_wallpaper_edit', array('{hash}' => $hash)));
                } else {
                    redirect($this->route_links->get('upload_wallpaper'));
                }
            }
        }


        $this->tpl->breadcrumbs['上传壁纸'] = $this->route_links->build_link('upload_wallpaper');
        $this->tpl->breadcrumbs['编辑 - ' . $hash] = 'active';

        $this->tpl->contents [] = $this->tpl->fetch('contents/upload_page', $data);
        $this->tpl->render('layouts/home');
    }

    public function delete($hash = false)
    {
        if (!$hash)
            redirect();
        $this->load->model(array('wallpaper_model'));
        $wallpaper = $this->wallpaper_model->get_wallpaper(array(
            'user_seq_id' => $this->user->get_id(),
            'wallpaper_hash' => $hash,
            'cache_off' => true
        ));
        if (!$wallpaper) {
            $this->session->set_flashdata('ERROR', '壁纸ID有误');
            redirect($this->route_links->get('upload_wallpaper'));
        }
        $file = FCPATH . ORIGINALS_FOLDER_WF . '/' . $wallpaper->wallpaper_image_path;
        if (file_exists($file))
            @unlink($file);
        $this->wallpaper_model->deleteByIDs($wallpaper->wallpaper_seq_id);
        $this->session->set_flashdata('SUCCESS', '壁纸删除成功');
        redirect($_SERVER['HTTP_REFERER']);
    }
}
